using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Build;
using UnityEditor.AddressableAssets.Build.DataBuilders;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEngine;
using UnityEngine.AddressableAssets;

public class AddressableTools: EditorWindow
{
    private static string cdnUrl = $"http://127.0.0.1:8900/Addressable";
    static string version = "1.0";

    [MenuItem("AddressableTools/PackAssets")]
    public static void OpenWindows()
    {
        AddressableTools win = GetWindow<AddressableTools>("AddressableTools");
        win.Show();
    }

    void OnGUI()
    {

        GUILayout.BeginVertical();
        GUILayout.BeginHorizontal();
        version = GUILayout.TextArea(version);
        GUILayout.Space(10);
        if (GUILayout.Button("设置版本"))
        {
            SetVersion();
        }
        GUILayout.EndHorizontal();
        GUILayout.Space(10);
        if (GUILayout.Button("生成Profile"))
        {
            SetProfile();
        }
        GUILayout.Space(10);
        if (GUILayout.Button("设置分组"))
        {
            SetGroup();
        }
        GUILayout.Space(10);
        if (GUILayout.Button("打首包"))
        {
            BuildAssets();
        }
        if (GUILayout.Button("增量打包"))
        {
            UpdateAssets();
        }
        GUILayout.Space(10);
        if (GUILayout.Button("一键首包"))
        {
            PackAssets();
        }
        GUILayout.EndVertical();
    }
    
    public static void PackAssets()
    {
        SetVersion();
        SetProfile();
        SetGroup();
        BuildAssets();
        AssetDatabase.Refresh();
    }

    /// <summary>
    /// 创建自己的 Profile 或者用默认的 
    /// </summary>
    static void SetProfile()
    {
        var profileId = AddressableAssetSettingsDefaultObject.Settings.profileSettings.AddProfile("MyProfile", null);
        AddressableAssetSettingsDefaultObject.Settings.profileSettings.SetValue(profileId, "BuildTarget",
            EditorUserBuildSettings.activeBuildTarget.ToString());
        AddressableAssetSettingsDefaultObject.Settings.profileSettings.SetValue(profileId, "Remote.LoadPath", cdnUrl);
    }
    /// <summary>
    /// 添加Group
    /// </summary>
    /// <param name="clearCache"></param>
    static void SetGroup(bool clearCache = false)
    {
        List<string> groupPaths = new List<string>() // 文件夹方式分组
        {
            "Prefabs",
            "Materials",
            "Scenes",
        };
        if (clearCache)
        {
            AddressableAssetSettingsDefaultObject.Settings.groups.Clear();
        }

        Debug.Log(AddressableAssetSettingsDefaultObject.Settings.groups.Count);
        // return;
        foreach (var groupPath in groupPaths)
        {
            int index = AddressableAssetSettingsDefaultObject.Settings.groups.FindIndex(x => x.Name == groupPath);
            AddressableAssetGroup group;
            if (index < 0)
            {
                group = AddressableAssetSettingsDefaultObject.Settings.CreateGroup(groupPath, false, false, false, null,
                    new Type[]
                    {
                        typeof(AddressableAssetGroupSchema),
                        typeof(BundledAssetGroupSchema),
                        typeof(ContentUpdateGroupSchema),
                    });
                AssetDatabase.SaveAssets();
            }
            else
            {
                group = AddressableAssetSettingsDefaultObject.Settings.groups[index];
            }
            var mBAGSchema = group.GetSchema(typeof(BundledAssetGroupSchema)) as BundledAssetGroupSchema;
            mBAGSchema.BuildPath.SetVariableByName(group.Settings , "Remote.BuildPath");
            mBAGSchema.LoadPath.SetVariableByName(group.Settings , "Remote.LoadPath");
            
            string path = "Assets/" + groupPath;
            string guid = AssetDatabase.AssetPathToGUID(path);
            var entry = AddressableAssetSettingsDefaultObject.Settings.CreateOrMoveEntry(guid, group);
        }
    }

    static void SetVersion()
    {
        AddressableAssetSettingsDefaultObject.Settings.OverridePlayerVersion = version; 
    }

    static void BuildAssets()
    {
        AddressableAssetSettings.BuildPlayerContent();
    }
    static void UpdateAssets()
    {
        var path = Path.GetDirectoryName(Application.dataPath) + "/" + Addressables.LibraryPath + PlatformMappingService.GetPlatformPathSubFolder() + "/addressables_content_state.bin";
        if (!string.IsNullOrEmpty(path))
            ContentUpdateScript.BuildContentUpdate(AddressableAssetSettingsDefaultObject.Settings, path);
    }
}